package view.listeners;

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import model.Constants;
import model.HostAddress;
import model.IPAddress;
import model.Subnet;
import view.components.SubnetComboBox;
import view.dialogs.MultiInfoDialog;
import view.views.dialogContentViews.MultiListPanel;
import controller.Controller;
import controller.DialogDisposer;

public class MultiIpListener implements ActionListener {

	private final Window comp;
	private final SubnetComboBox subnetCombo;

	public MultiIpListener(Window comp,
			SubnetComboBox subnetCombo) {
		this.comp = comp;
		this.subnetCombo = subnetCombo;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		MultiListPanel ipList = Controller.getInstance().getMultiList();
		ArrayList<IPAddress> addresses = new ArrayList<IPAddress>();
		if (ipList != null) {

			int count = (Integer) ipList.getSizeComboBox().getBox()
					.getSelectedItem();

			if (!subnetCombo.getBox().getSelectedItem().equals(Constants.EMPTY)) {

				Subnet sub = subnetCombo.getMap().get(
						subnetCombo.getBox().getSelectedItem());

				ArrayList<HostAddress> hostList = Controller.getInstance()
						.getHosts();
				int indexHost = 0, indexSub = 0;
				for (HostAddress element : hostList) {
					boolean found = false;
					for (Subnet subnet : element.getSubnetList()) {
						if (sub.getNetAdress().getAddress()
								.equals(subnet.getNetAdress().getAddress())) {
							found = true;
							break;
						}
						indexSub++;
					}
					if (found) {
						break;
					}
					indexHost++;
					indexSub = 0;
				}

				Controller.getInstance().setIndexHost(indexHost);
				Controller.getInstance().setIndexSub(indexSub);

				for (IPAddress element : sub.getIpAddressList()) {

					if (count != 0
							&& element.getAdditionalInfo().equals(
									Constants.FREEIP)) {
						addresses.add(element);
						count--;
					}
				}
				Controller.getInstance().setMultiIpList(addresses);
				Thread t = new Thread(new DialogDisposer(comp));
				t.start();
				new MultiInfoDialog(Constants.MULTIADDTITLE);

			}
		}

	}

}
